﻿using BBCore.Application.ViewModels.Admins;
using BBCore.Core.Models.Admins;
using BBCore.Infrastructure.Helps;
using BBCore.Server.Components.Pages;
using BBCore.Server.Components.Pages.Admins;
using BootstrapBlazor.Components;
using DocumentFormat.OpenXml.Vml.Office;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security.Claims;

namespace BBCore.Server.Components.Shared
{
    /// <summary>
    /// 
    /// </summary>
    public sealed partial class MainLayout
    {
     
        private bool UseTabSet { get; set; } = true;

        private string Theme { get; set; } = "";

        private bool IsOpen { get; set; }

        private bool IsFixedHeader { get; set; } = true;

        private bool IsFixedFooter { get; set; } = true;

        private bool IsFullSide { get; set; } = true;

        private bool ShowFooter { get; set; } = true;

        private List<MenuItem>? Menus { get; set; }

        private ClaimsPrincipal? _user;
        private UserEntity? _userEntity;

        //private List<string> _authUrl = new List<string>();

        /// <summary>
        /// OnInitialized 方法
        /// </summary>
        protected override void OnInitialized()
        {
            base.OnInitialized();            
            //订阅 消息通知
            DispatchService.Subscribe(Notify);
        }


        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            _user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
            
            if (_user == null)
            {
                return;
            }

            var userName = _user.FindFirst(ClaimTypes.Name)?.Value;
            _userEntity = IAdminService.user_Login(userName!);
            RefreshMenu();

        }
        private string? IP { get; set; }
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            await base.OnAfterRenderAsync(firstRender);
            if (firstRender)
            {
                IP = _httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "";
                Update();
            }
        }


        /// <summary>
        /// 刷新菜单
        /// </summary>
        private void RefreshMenu()
        {
            var roleId = _user!.FindFirst(ClaimTypes.Role)?.Value;
            if (roleId == null)
            {
                return;
            }
            var role = IAdminService.role_Role(int.Parse(roleId));
            if (role == null || role.Menus == null)
            {
                return;
            }
            //_authUrl = role.Menus.Select(x => x.Url!).ToList();
            Menus = IAdminService.menu_CascadingMenu(role.Menus, 0);
        }

        /// <summary>
        /// 更新组件方法
        /// </summary>
        public void Update() => StateHasChanged();


        private bool AnnouncementsKey;

        /// <summary>
        /// 通知实现方法 Notify
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        private async Task Notify(DispatchEntry<string> payload)
        {
            //if (payload.Name == BBCore_Constant.RefreshMenuKey && payload.Entry==_userEntity?.RoleId.ToString())
            //{
            //    RefreshMenu();
            //    await InvokeAsync(StateHasChanged);
            //    await ToastService.Show(new ToastOption()
            //    {
            //        Title = "菜单更新",
            //        Content = "菜单有新增"
            //    });

            //}
            if (payload.Entry != null)
            {
                await ToastService.Show(new ToastOption()
                {
                    Title = payload.Name,
                    Content = payload.Entry,
                    Category = ToastCategory.Information,
                    Delay = 60 * 1000,//1分钟
                    ForceDelay = true//强制使用本实例的延时时间，防止值被全局配置覆盖
                });
                AnnouncementsKey=!AnnouncementsKey;
                await InvokeAsync(StateHasChanged);//适用于需要等待异步操作（如数据加载）完成后再更新UI的场景

                //StateHasChanged‌：适用于那些不需要等待异步操作完成的场景，例如组件内部状态变化、接收到外部数据变化或用户触发事件等‌

            }

        }
        /// <summary>
        /// 页面或者组件销毁时 取消订阅
        /// </summary>
        public void Dispose()
        {
            DispatchService.UnSubscribe(Notify);
        }


        private void ChangePassword()
        {

            DialogService.Show(new DialogOption()
            {
                ShowFooter = false,
                Title = "修改密码",
                Size = Size.Medium,

                BodyTemplate = BootstrapDynamicComponent.CreateComponent<ChangePassword>(new Dictionary<string, object?>()
                {
                    [nameof(BBCore.Server.Components.Pages.Admins.ChangePassword.UserEntity)] = _userEntity
                }).Render()
            });
        }

        [Inject]
        [NotNull]
        private SwalService? SwalService { get; set; }


        private async Task OnErrorHandleAsync(ILogger Logger, Exception ex)
        {
            nlogILogger?.LogError("全局异常信息:\r\n" + ex.ToString() + "\r\n");
            await SwalService.Show(new SwalOption()
            {
                Category = SwalCategory.Error,
                Title = "程序出错了!",
                Content = "出错信息:" + ex.Message,
                ShowFooter = true,
                FooterTemplate = BootstrapDynamicComponent.CreateComponent<BBCore.Server.Components.Pages.ContactAdmin>().Render()
            });
        }

    }
}
